package com.ec.file.service.impl;

import cn.hutool.core.io.FileUtil;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.CreateBucketRequest;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.ec.core.common.utils.CoreToolUtil;
import com.ec.core.secure.utils.SecureUtil;
import com.ec.file.props.AliyunOssProperties;
import com.ec.file.service.IOssService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.UUID;

/**
 * <p>
 *
 * </p>
 *
 * @author Eric Lee
 * @since 2019-07-18 15:35
 */
@Slf4j
@Service
public class OssServiceImpl implements IOssService {
    @Autowired
    private AliyunOssProperties aliOss;
    @Autowired
    private OSS ossClient;

    @Override
    public String fileUpload2Local(MultipartFile file, String savePath, Boolean isRename) throws IOException {
        String filename = file.getOriginalFilename();
        File path = new File(savePath);
        if (!path.exists()) {
            path.mkdir();
        }
        //是否重命名
        if (isRename) {
            filename = UUID.randomUUID().toString().replace("-", "")
                    + filename.substring(filename.lastIndexOf("."));
        }
        String filePath = path + "/" + filename;
        file.transferTo(new File(filePath));
        return filePath;
    }

    @Override
    public String fileUpload2Oss(File file, Boolean isRename) throws OSSException, ClientException {
        if (file == null) {
            return null;
        }
        String fileUrl;
        if (isRename) {
            fileUrl = UUID.randomUUID().toString().replace("-", "")
                    + file.getName().substring(file.getName().lastIndexOf("."));
        } else {
            fileUrl = FileUtil.getName(file);
        }

        String url = "";
        if (!ossClient.doesBucketExist(aliOss.getBucketName())) {
            ossClient.createBucket(aliOss.getBucketName());
            CreateBucketRequest createBucketRequest = new CreateBucketRequest(aliOss.getBucketName());
            createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
            ossClient.createBucket(createBucketRequest);
        }
        PutObjectResult uploadResult = ossClient.putObject(new PutObjectRequest(aliOss.getBucketName(), fileUrl, file));
        ossClient.setBucketAcl(aliOss.getBucketName(), CannedAccessControlList.PublicRead);
        if (CoreToolUtil.isNotEmpty(uploadResult)) {
            //url = aliOss.getEndPoint().replace("https://", "https://" + aliOss.getBucketName() + ".") + "/" + fileUrl;
            url = fileUrl;
        }
        return url;
    }

    @Override
    public String webFileUpload2Oss(String urlList, String path, Boolean isRename) throws IOException {
        if (StringUtils.isBlank(urlList)) {
            return "";
        }
        URL url;
        String dir = path + UUID.randomUUID() + urlList.substring(urlList.lastIndexOf("."));
        FileOutputStream fileOutputStream = null;
        InputStream inputStream = null;
        try {
            url = new URL(urlList);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:55.0) Gecko/20100101 Firefox/55.0");
            connection.setConnectTimeout(10 * 1000);
            connection.setReadTimeout(15 * 1000);
            inputStream = connection.getInputStream();
            byte[] buffer = new byte[1024];
            int length;
            fileOutputStream = new FileOutputStream(dir);
            while (-1 != (length = inputStream.read(buffer))) {
                fileOutputStream.write(buffer, 0, length);
            }
        } catch (Exception e) {
            log.error("下载web文件失败：{}", e.getMessage());
            throw new IOException("下载web文件失败");
        } finally {
            inputStream.close();
            fileOutputStream.flush();
            fileOutputStream.close();
        }
        File file = new File(dir);
        String headPath = this.fileUpload2Oss(file, isRename);
        FileUtils.deleteQuietly(file);
        return headPath;
    }
}
